<?php


$news_tweak = new Tweak( "News Page tweak" );

$news_tweak->author("Zorchenhimer");

$news_tweak->description("A multi-page news/blog post tweak");

$news_tweak->addInterface('news_show_options');
$news_tweak->addTweak('news-page', 'news_display_posts');
/*
	this is my attempt at a news page tweaker.
*/


function _debug($info, $block=null) {
	if( NEWS_DEBUG ) {
		echo "<div class=\"msgbox\">$info</div>";
	}
}

function news_load_config($admin=false) {
		$config_file = 'news/config.txt';
	if( !$admin )
		$config_file = NANO_TWEAKS_DIR.$config_file;
	else
		$config_file = "tweaks/$config_file";

	$config = array();
	$config = file($config_file);
	$config = unserialize($config[0]);
	return $config;
}

function news_save_config( $data ) {
	$config_file = 'tweaks/news/config.txt';
	$data = serialize( str_replace("\n",'',$data) );
	put2file($config_file, $data);
}

//  Makes a new file for each post, for pagation
function news_write_post($post, $title) {
	$cfg = news_load_config(true);
	$newsdir = "pages/news/";
	$post = str_replace("\n", "<br />\n", $post);
	$currentDate = date("d/m/y h:i A");
	if( $post == $title && $post == 'firstrun' ) { // Make the default post
		$postdata = "<h2>First Post!</h2>
			<p>You haven't made any news posts yet!  Go to the admin pannel and make one.  :)</p>";
		$postfile = "firstrun.php";
	} else {		
		$postdata = '<div class="displayNewsHeading">'.htmlentities($title).'</div>
                    <div class="displayDate">'.$currentDate.'</div>
                      <div class="displayPost"><p>'.$post.'</p><br /></div>';
                   
                      
		$postfile = time() . ".php";
	}
	
	if( put2file($newsdir . $postfile, $postdata) ) {
			echo '<div class="msgbox" style="float: left; width: 600px">Post Sucessful!</div>';
	} else {
		echo '<div class="msgbox" style="float: left; width: 600px">Error: Unable to create post!</div>';
	}		
	echo '<div style="clear: left">&nbsp;</div>';
	
}

function news_first_run() {
	_debug( "First run" );
	
	// make the new page if it doesn't exist
	$pagesdata = file('pagesdata.txt');
	$pagesdata = unserialize( $pagesdata[0] );
	$foundit = false;
	$highkey = 0;
	foreach( $pagesdata['slugs'] as $key=>$value ) {
		if( $value == "news" ) {
			_debug( "found news page: $key\n" );
			_debug( "newspage title: ".$pagesdata['titles'][$key] ."\n" );
			$foundit = true;
		}
		if( $highkey < $key )
			$highkey = $key;
	}
	
	if( !$foundit ) { // create the page
		_debug( 'Creating the page' );
		$x = $highkey + 1;
		$pagesdata['slugs'][$x] = 'news';
		$pagesdata['titles'][$x] = 'News';
		$y = 0;
		foreach( $pagesdata['links_cats']['sidebar'] as $key=>$val ) {
			if( $y < $key )
				$y = $key;
		}
		$y++;
		$pagesdata['links_cats']['sidebar'][$y] = $x;
		$newdata = serialize( $pagesdata );
		put2file( 'pagesdata.txt', $newdata );
		put2file( 'pages/news.php', "<!-- This page was automatically generated  -->\n<?php runTweak('news-page')?>" );
		news_write_post('firstrun','firstrun');
	}
	
	//  Create the news directory for the posts.
	if( !file_exists("pages/news/") ) {
		if( mkdir( "pages/news" ) ) // defaults to 777  (rwxrwxrwx)
			_debug( "News direcotory sucessfully created" );
		else {
			_debug( "Failed to create news directory!" );
			die( "Fatal error" );
		}
	} else {
		_debug( "news directory already exists" );
	}
}

function news_settings() {
	if( $posted = $_POST )
		news_save_config($posted);

	$cfg = news_load_config(true);
	$sel = ' selected="selected" ';
	switch( $cfg['postspage'] ) {
		case 5:
			$one = $sel;
			break;
		case 10:
			$two = $sel;
			break;
		case 15:
			$three = $sel;
			break;
		case 20:
			$four = $sel;
			break;
		case 25:
			$five = $sel;
			break;
		case 50:
			$six = $sel;
			break;
	}
	echo '
	<p><a href="?tweak=news-page-tweak">Back</a></p>
	<object><form action="#" method="post">
		Posts per Page: <select name="postspage">'."
				<option$one>5</option>
				<option$two>10</option>
				<option$three>15</option>
				<option$four>20</option>
				<option$five>25</option>
				<option$six>50</option>".'
			</select><br />
		<!--input type="checkbox" name="debug"';
		if( $cfg['debug'] == 'on' )
			echo ' checked="checked" ';
		echo ' /> Debug<br /--><br />
		<br />
		<input type="submit" value="Save" />
		</form></object>';
}

function news_show_options() {
	if( !file_exists( "pages/news/firstrun.php" ) )
		news_first_run();
	
	$error = false;
	if( $_POST['posted'] ) {
		if( !($post = $_POST['newsdata']) ) {
			echo "<div class=\"redbox\">No news to post!</div>";
			$error = true;
		}
		if( !($title = $_POST['title']) ) {
			echo "<div class=\"redbox\">No date or title given!</div>";
			$error = true;
		}
		
		if( !$error )

			news_write_post($post, $title);
			
		if( $error ) {
			$giventitle = $_POST['title'];
			$givenpost = $_POST['newsdata'];
		}
	} 
	
	if ($_GET['r'] == 'settings')
		news_settings();
	else {
	  $currentDate = date("d/m/y");
		echo '<p><a href="?tweak=news-page-tweak&r=settings">Settings</a></p>

			<!--h3>News Page</h3-->
			<h3>New Post</h3>';
		runTweak( 'add-form-display' );
		echo'
			 <object><form action="#" method="post">
			   <div class="news">
				  <div class="newsTitle">Title: <input maxlength="30" size="25" type="text" name="title" value="'.$giventitle.'" /></div>
          <div class="newsDate">Date: '.$currentDate.'</div>
				  <div class="newsPost"><textarea rows="10" cols="80" name="newsdata">'.$givenpost.'</textarea>
				    <input type="text" value="posted" name="posted" style="display: none" /><br />
				    <input type="Submit" value="Post" /></div>
			   </div>
			 </form></object>';
		runTweak( 'after-add-form-display' );
	}
}

function news_display_posts() {  // the function call for this belongs in the news page
	$cfg = news_load_config();
	$postpage = $cfg['postspage'];// posts per page
	
	$postdir = str_replace(NANO_PAGES_DIR.'news/','',glob( NANO_PAGES_DIR."news/*.php" ));

	$posts = array();
	foreach( $postdir as $obj ) {
		if( $obj != '.' && $obj != '..' && $obj != 'firstrun.php' && strstr( $obj, ".php") )
			$posts[] = $obj;
	}
	
	if( !$posts[0] )
		include 'admin/pages/news/firstrun.php';
	else {
		$countpost = count($posts);
		
		if ( $_GET['p'] )
			$pg = $_GET['p'];
		else
			$pg = 1;

		$x = ($countpost - ($postpage * ($pg -1))) -1;		
		$count = 0;
		
		while( $count < $postpage ) {
			include NANO_PAGES_DIR."news/$posts[$x]";
			$count++;
			$x--;
		}
		
		if( $pg == 1 ) {  // first page?
			$newerlinktext = "";
		} else {
			$tmp = $pg - 1;
			$newerlinktext = '<a href="?'.NANO_SLUGWORD.'=news&p='.$tmp.'">&gt;&gt; Newer &gt;&gt;</a>';
		}
		
		if( $x < 0 ) {  // last page?
			$olderlinktext = '';
		} else {
			$tmp = $pg + 1;
			$olderlinktext = '<a href="?'.NANO_SLUGWORD.'=news&p='.$tmp.'">&lt;&lt; Older Posts &lt;&lt;</a>';
		}
		echo "<div style=\"float: left\">$olderlinktext</div>";  //  "<< Older Posts <<"
		echo "<div style=\"float: right\">$newerlinktext</div>";  //  ">> Newer Posts >>"
		
	}
}

?>
